﻿using UnityEditor;
using UnityEngine;
using System.IO;

public class MetaFileDeleter : EditorWindow
{
    private bool deleteFromAssets = true;
    private string customPath = "";

    [MenuItem("Miao/Tools/删除 .meta 文件")]
    public static void ShowWindow()
    {
        GetWindow<MetaFileDeleter>("Meta 文件删除工具");
    }

    private void OnGUI()
    {
        GUILayout.Label("删除指定目录下的所有 .meta 文件", EditorStyles.boldLabel);

        // 选择删除模式
        deleteFromAssets = EditorGUILayout.Toggle("从 Assets 目录开始", deleteFromAssets);

        if (!deleteFromAssets)
        {
            customPath = EditorGUILayout.TextField("自定义路径", customPath);
        }

        if (GUILayout.Button("选择目录"))
        {
            string startPath = deleteFromAssets ? Application.dataPath : Application.dataPath + "/..";
            string selectedPath = EditorUtility.OpenFolderPanel("选择目录", startPath, "");

            if (!string.IsNullOrEmpty(selectedPath))
            {
                if (EditorUtility.DisplayDialog("确认删除",
                    $"确定要删除 {selectedPath} 目录下的所有 .meta 文件吗？\n此操作不可恢复！",
                    "确认", "取消"))
                {
                    DeleteMetaFiles(selectedPath);
                    if (IsProjectPath(selectedPath))
                    {
                        AssetDatabase.Refresh();
                    }
                    ShowNotification(new GUIContent("已完成 .meta 文件删除"));
                }
            }
        }
    }

    private void DeleteMetaFiles(string directoryPath)
    {
        if (!Directory.Exists(directoryPath))
        {
            Debug.LogError($"目录不存在: {directoryPath}");
            return;
        }

        string[] metaFiles = Directory.GetFiles(directoryPath, "*.meta", SearchOption.AllDirectories);
        int deletedCount = 0;

        foreach (string metaFile in metaFiles)
        {
            try
            {
                File.Delete(metaFile);
                deletedCount++;
            }
            catch (System.Exception e)
            {
                Debug.LogError($"删除文件失败: {metaFile}\n{e.Message}");
            }
        }

        Debug.Log($"已删除 {deletedCount} 个 .meta 文件");
    }

    private bool IsProjectPath(string path)
    {
        return path.Contains(Application.dataPath);
    }
}